package com.jun.seckill_by_jun.rabbitmq;


import com.jun.seckill_by_jun.domain.SeckillOrder;
import com.jun.seckill_by_jun.domain.SeckillUser;
import com.jun.seckill_by_jun.redis.RedisService;
import com.jun.seckill_by_jun.service.GoodsService;
import com.jun.seckill_by_jun.service.OrderService;
import com.jun.seckill_by_jun.service.SeckillService;
import com.jun.seckill_by_jun.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MQReceiver {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SeckillService seckillService;

    @Autowired
    private OrderService orderService;

    private static Logger log = LoggerFactory.getLogger(MQReceiver.class);

    @RabbitListener(queues=MQConfig.SECKILL_QUEUE)
    public void receive(String message){
        log.info("receive message:"+message);
        //处理消息：
        SeckillMessage m = RedisService.stringToBean(message, SeckillMessage.class);
        SeckillUser user = m.getUser();
        long goodsId = m.getGoodsId();
        //判断是否有库存
        GoodsVo goodsVo = goodsService.getGoodsVoByGoodsId(goodsId);
        int stock = goodsVo.getStockCount();
        if(stock<=0){
            return;
        }
        //判断是否重复秒杀
        SeckillOrder order = orderService.getOrderByUserIdGoodsId(user.getId(), goodsId);
        if(order != null){
            return;
        }
        //生成订单
        seckillService.seckill(user,goodsVo);
    }

//    @RabbitListener(queues=MQConfig.QUEUE)
//    public void receive(String message){
//        log.info("receive message:"+message);
//    }
//
//    @RabbitListener(queues=MQConfig.TOPIC_QUEUE1)
//    public void receiveTopic1(String message){
//        log.info("topic1 receive message:" + message);
//    }
//
//    @RabbitListener(queues=MQConfig.TOPIC_QUEUE2)
//    public void receiveTopic2(String message){
//        log.info("topic2 receive message:"+message);
//    }
}
